import { _decorator, Collider, Component, ITriggerEvent, Node, sp } from 'cc';
import { Constant } from '../framework/Constant';
import { PoolManager } from '../framework/PoolManager';
const { ccclass, property } = _decorator;

const OUTOFRANGE = 50;
@ccclass('Bullet')
export class Bullet extends Component {

    private bulletSpeed = 0;

    private isEnemyBullet = false;

    private direction=Constant.Direction.MIDDLE;

    start() {

    }

    protected onEnable(): void {
        const collider = this.getComponent(Collider);
        collider.on('onTriggerEnter', this.triggerEnter, this);
    }
    protected onDestroy(): void {
        const collider = this.getComponent(Collider);
        collider.off('onTriggerEnter', this.triggerEnter, this);
    }
    show(speed: number, isEnemyBullet: boolean,direction=Constant.Direction.MIDDLE) {
        this.direction=direction;
        this.bulletSpeed = speed;
        this.isEnemyBullet = isEnemyBullet;
    }


    triggerEnter(event: ITriggerEvent) {
        // this.node.destroy();
PoolManager.instance().put(this.node);
    }

    update(deltaTime: number) {
        const pos = this.node.position;
        let moveLength = 0;
        let x=pos.x;
        if (this.isEnemyBullet) {
            moveLength = pos.z + this.bulletSpeed;
        } else {
            moveLength = pos.z - this.bulletSpeed;
            if(this.direction===Constant.Direction.LEFT){
                x-=this.bulletSpeed*0.3;
            }else if(this.direction===Constant.Direction.RIGHT){
                x+=this.bulletSpeed*0.3;
            }
        }
        this.node.setPosition(x, pos.y, moveLength);

        if (Math.abs(moveLength) > OUTOFRANGE) {
            PoolManager.instance().put(this.node);
        }
    }
}

